﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql;
using MySql.Data.MySqlClient;
using D2E.Shared.Common.Logger;
using D2E.Realm.Common;

namespace D2E.Realm.Database
{
    public class DatabaseManager
    {
        public string Server;
        public string Database;

        private string User;
        private string Password;

        private MySqlConnection Connection;
        private string ConnectionString;

        public DatabaseManager()
        {
            this.Server = Settings.BaseSettings.GetValue("Database.Host");
            this.Database = Settings.BaseSettings.GetValue("Database.Name");
            this.User = Settings.BaseSettings.GetValue("Database.Username");
            this.Password = Settings.BaseSettings.GetValue("Database.Password");
        }

        public DatabaseManager(string server, string database, string user, string password)
        {
            this.Server = server;
            this.Database = database;
            this.User = user;
            this.Password = password;
        }

        public void Open()
        {
            this.ConnectionString = string.Format(@"Server={0};Database={1};Uid={2};Pwd={3};", this.Server, this.Database, this.User, this.Password);

            try
            {
                Connection = new MySqlConnection(ConnectionString);
                Connection.Open();
                Logger.LogInfos(string.Format("MySQL Server '{0}' connected", this.Server));
            }
            catch (Exception e)
            {
                Logger.LogError(e.Message);
            }
        }

        public void Close()
        {
            try
            {
                this.Connection.Close();
                Logger.LogInfos(string.Format("MySQL Server '{0}' disconnected", this.Server));
            }
            catch (Exception e)
            {
                Logger.LogError(e.Message);
            }
        }

        public void Query(string query)
        {
            try
            {
                MySqlCommand command = new MySqlCommand(query, this.Connection);
                command.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                Logger.LogError(e.Message);
            }
        }      
    }
}
